package com.infisight.hudprojector.fragment;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.infisight.hudprojector.R;
import com.infisight.hudprojector.adapter.PhoneConnectAdapter;
import com.infisight.hudprojector.data.DataMoreLevelClass;
import com.infisight.hudprojector.data.PMessage;
import com.infisight.hudprojector.data.PhoneInfoDataClass;
import com.infisight.hudprojector.data.PhoneInfoDataListClass;
import com.infisight.hudprojector.data.SpeechVoiceData;
import com.infisight.hudprojector.data.VoiceDataClass;
import com.infisight.hudprojector.kdxfspeech.SpeechVoiceCompound;
import com.infisight.hudprojector.kdxfspeech.SpeechVoiceRecognition;
import com.infisight.hudprojector.service.MusicService;
import com.infisight.hudprojector.util.CommonUtil;
import com.infisight.hudprojector.util.Constants;
import com.infisight.hudprojector.widget.CircularImage;

@SuppressLint("NewApi")
public class PhoneFragment extends Fragment {

	public static String TAG = "PhoneFragment";
	SpeechVoiceCompound svc;
	SpeechVoiceRecognition svr;
	Gson gson = null;
	ImageView fp_im_hang_up;
	CircularImage fp_im_person_icon;
	TextView fp_tv_phone_name, fp_tv_phone_number, fp_tv_phone_location,
			fp_tv_phone_time, fg_tv_phone_no_person;
	PhoneConnectAdapter groupAdapter;
	private PopupWindow popupWindow;

	LinearLayout fh_ll_001, fh_ll_003;
	private ListView lv_group;
	private View view;
	int onTelTime = 0;
	Timer timer = new Timer();
	SharedPreferences sp;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			onTelTime += msg.what;
			fp_tv_phone_time.setText(CommonUtil.secToTime(onTelTime));
			super.handleMessage(msg);
		}
	};

	TimerTask task = new TimerTask() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			// 由于主线程安全，页面的更新需放到主线程中
			Message msg = new Message();
			msg.what = 1;
			handler.sendMessage(msg);
		}
	};

	public static PhoneFragment newInstance() {
		Log.i(TAG, "PhoneFragment newInstance");
		PhoneFragment fragment = new PhoneFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	public PhoneFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		init();
		sp = getActivity().getSharedPreferences("bg_music_info", 0);
		fp_im_person_icon.setImageResource(R.drawable.phone_person);
		svr = new SpeechVoiceRecognition(getActivity(), "", null);// 语音识别
		svc = SpeechVoiceCompound.getInstance(getActivity(), "", svr);// 语音合成

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment

		return inflater.inflate(R.layout.fragment_phone, container, false);
	}

	/**
	 * 初始化AMap对象
	 */
	private void init() {
		gson = new Gson();
		fp_im_person_icon = (CircularImage) getActivity().findViewById(
				R.id.fp_im_person_icon);// 联系人头像
		fp_tv_phone_name = (TextView) getActivity().findViewById(
				R.id.fp_tv_phone_name);// 联系人姓名
		fp_tv_phone_number = (TextView) getActivity().findViewById(
				R.id.fp_tv_phone_number);// 联系人手机号
		fp_tv_phone_location = (TextView) getActivity().findViewById(
				R.id.fp_tv_phone_location);// 号码归属地
		fp_tv_phone_time = (TextView) getActivity().findViewById(
				R.id.fp_tv_phone_time);// 通话时长
		fp_im_hang_up = (ImageView) getActivity().findViewById(
				R.id.fp_im_hang_up);// 挂断按钮
		fg_tv_phone_no_person = (TextView) getActivity().findViewById(
				R.id.fg_tv_phone_no_person);// 没有找到联系人

		fh_ll_001 = (LinearLayout) getActivity().findViewById(R.id.fh_ll_001);
		fh_ll_003 = (LinearLayout) getActivity().findViewById(R.id.fh_ll_003);
		Bundle bundle = getArguments();
		Log.i(TAG, bundle.toString());
		String phoneInfo = bundle.getString("phoneInfos");
		Log.i(TAG, phoneInfo);
		if (phoneInfo != null) {
			sendMsg(Constants.MODEL_PHONE_NAME_COM, phoneInfo);

			// Intent intent = new Intent(Intent.ACTION_CALL,
			// Uri.parse("tel:17802118921"));
			// getActivity().startActivity(intent);
			// fp_tv_phone_name.setText("林啸 ");
			// fp_tv_phone_number.setText("17802118921");
			// fp_tv_phone_location.setText("上海浦东");
			// fp_tv_phone_time.setText("00:01:02");

		} else {

		}

	}

	BroadcastReceiver phoneReceiver = new BroadcastReceiver() {

		@SuppressWarnings("deprecation")
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			gson = new Gson();
			final String action = intent.getAction();
			SpeechVoiceData svd;
			VoiceDataClass vdc;
			Log.i(TAG, "phoneReceiver:" + action);
			try {
				// 主页跳转电话界面跳转
				if (action != null
						&& Constants.MAIN_PHONE_ACTION.equals(action)) {
					svd = gson.fromJson(
							intent.getStringExtra(Constants.MAIN_PHONE_ACTION),
							SpeechVoiceData.class);
					svd.setCommand(Constants.MAIN_PHONE_COM);
					CommonUtil.processBroadcast(getActivity(), svd);
					fg_tv_phone_no_person.setVisibility(View.GONE);
					// 处理电话信息
				} else if (action != null
						&& (Constants.MODEL_PHONE_ACTION.equals(action) || Constants.COMMON_UTIL_ACTION
								.equals(action))) {
					// 语音消息的处理
					svd = gson.fromJson(intent.getStringExtra(action),
							SpeechVoiceData.class);
					if (svd != null) {
						if (svd.getValue() != null) {
							vdc = gson.fromJson(svd.getValue(),
									VoiceDataClass.class);
							// 打电话给某人
							if (vdc.getType().equals(Constants.F_R_PHONE_TO[0])) {
								fg_tv_phone_no_person.setVisibility(View.GONE);
								if (popupWindow != null
										&& popupWindow.isShowing()) {
									onDismiss();
									popupWindow.dismiss();
									sendMsg(Constants.MODEL_PHONE_NAME_COM,
											vdc.getValue());
								}
							}
							// 语音挂断
							else if (vdc.getValue() != null
									&& vdc.getValue().equals(
											Constants.F_R_PHONE_HANG_UP[1])) {
								sendMsg(Constants.MODEL_PHONE_HANG_UP_COM,
										vdc.getValue());
								CommonUtil.retHomeFragment(getActivity());
								fg_tv_phone_no_person
										.setVisibility(View.VISIBLE);
								fh_ll_001.setVisibility(View.GONE);
								fh_ll_003.setVisibility(View.GONE);

							}
							// 选择联系人
							else if (vdc.getType().equals(
									Constants.F_R_CHOOSE_ITEM[0])) {
								int index = CommonUtil.getIndex(vdc.getValue());

								PhoneInfoDataClass pidc = groupAdapter.lists
										.get(index);

								fp_tv_phone_name.setText(pidc.getPhoneName());
								fp_tv_phone_number.setText(pidc
										.getPhoneNumber());
								fp_tv_phone_location.setText(pidc
										.getPhoneLocation());
								timer.schedule(task, 10, 1000);// 通话时长
								if (pidc.getPhonePhoto() != null) {
									fp_im_person_icon.setImageBitmap(pidc
											.getPhonePhoto());
								} else {
									fp_im_person_icon
											.setImageResource(R.drawable.phone_person);
								}

								sendMsg(Constants.MODEL_PHONE_ITEM_CHOOSE_COM,
										pidc.getPhoneNumber());
								onDismiss();
								popupWindow.dismiss();
								if (pidc != null && pidc.getPhoneName() != null) {
									svc.startSpeaking("正在给"
											+ pidc.getPhoneName() + "打电话");
									fg_tv_phone_no_person
											.setVisibility(View.GONE);
									fh_ll_001.setVisibility(View.VISIBLE);
									fh_ll_003.setVisibility(View.VISIBLE);
								}
							}
							// 下翻页
							else if (vdc.getType().equals(
									Constants.F_R_PHONE_PAGE_DOWN[0])) {
								int footNum = lv_group.getFooterViewsCount();
								if (footNum == groupAdapter.lists.size()) {
									svc.startSpeaking("已翻至底部");
								} else {
									lv_group.smoothScrollToPosition(footNum + 1);
								}
							}
							// 上翻页
							else if (vdc.getType().equals(
									Constants.F_R_PHONE_HANG_UP[0])) {
								int footNum = lv_group.getHeaderViewsCount();
								if (footNum == 0) {
									svc.startSpeaking("已翻至顶部");
								} else {
									lv_group.smoothScrollToPosition(footNum - 1);
								}
							}
						}
					} else {
						// 呼出电话信息回传
						String strExtra = intent
								.getStringExtra(Constants.MSG_PARAM);
						DataMoreLevelClass dmlc = gson.fromJson(strExtra,
								DataMoreLevelClass.class);
						switch (dmlc.getCommand()) {
						case Constants.MODEL_PHONE_NAME_COM:// 说联系人
							PhoneInfoDataListClass lsts = gson.fromJson(
									dmlc.getContent(),
									PhoneInfoDataListClass.class);
							Log.i(TAG, "MODEL_PHONE_NAME_COM:"
									+ Constants.MODEL_PHONE_NAME_COM);
							if (lsts.getPhoneInfoDataClass() != null
									&& lsts.getPhoneInfoDataClass().size() != 0) {

								if (lsts.getPhoneInfoDataClass().size() == 0) {
									fg_tv_phone_no_person
											.setVisibility(View.VISIBLE);
									svc.startSpeaking("没有找到相关联系人");
								} else if (lsts.getPhoneInfoDataClass().size() == 1) {

									PhoneInfoDataClass pidc = lsts
											.getPhoneInfoDataClass().get(0);
									fp_tv_phone_name.setText(pidc
											.getPhoneName());
									fp_tv_phone_number.setText(pidc
											.getPhoneNumber());
									fp_tv_phone_location.setText(pidc
											.getPhoneLocation());
									timer.schedule(task, 10, 1000);// 通话时长
									if (pidc.getPhonePhoto() != null) {
										fp_im_person_icon.setImageBitmap(pidc
												.getPhonePhoto());
									} else {
										fp_im_person_icon
												.setImageResource(R.drawable.phone_person);
									}
									fg_tv_phone_no_person
											.setVisibility(View.GONE);
									fh_ll_001.setVisibility(View.VISIBLE);
									fh_ll_003.setVisibility(View.VISIBLE);
								} else {

									showWindow(lsts.getPhoneInfoDataClass());
								}
							} else {
								fg_tv_phone_no_person
										.setVisibility(View.VISIBLE);
								svc.startSpeaking("没有找到相关联系人");
							}
							break;
						case Constants.MODEL_PHONE_HANG_UP_COM:// 挂断电话
							timer.cancel();
							onTelTime = 0;
							CommonUtil.retHomeFragment(getActivity());
							fg_tv_phone_no_person.setVisibility(View.VISIBLE);
							fh_ll_001.setVisibility(View.GONE);
							fh_ll_003.setVisibility(View.GONE);
						default:
							break;
						}

					}
				}
				// 返回首页
				else if (action != null
						&& Constants.MAIN_RETURN_HOME_ACTION.equals(action)) {
					Log.i(TAG, action + "action");
					CommonUtil.retHomeFragment(getActivity());
					fg_tv_phone_no_person.setVisibility(View.VISIBLE);
					fh_ll_001.setVisibility(View.GONE);
					fh_ll_003.setVisibility(View.GONE);
				}
				// 电话界面导航
				else if (action != null
						&& Constants.MAIN_NAVI_ACTION.equals(action)) {

					svd = gson.fromJson(
							intent.getStringExtra(Constants.MAIN_NAVI_ACTION),
							SpeechVoiceData.class);

					svd.setCommand(Constants.MAIN_NAVI_COM);

					Log.i(TAG,
							intent.getStringExtra(Constants.MAIN_NAVI_ACTION));
					CommonUtil.processBroadcast(getActivity(), svd);
				}
				// 电话界面显示obd
				else if (action != null
						&& Constants.MAIN_OBD_ACTION.equals(action)) {

					svd = gson.fromJson(
							intent.getStringExtra(Constants.MAIN_OBD_ACTION),
							SpeechVoiceData.class);
					vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);

					svd.setCommand(Constants.MAIN_OBD_COM);
					svd.setValue(vdc.getValue());
					CommonUtil.processBroadcast(getActivity(), svd);
				}
				// 音乐功能
				else if (action != null
						&& Constants.MAIN_MUSIC_ACTION.equals(action)) {
					svd = gson.fromJson(
							intent.getStringExtra(Constants.MAIN_MUSIC_ACTION),
							SpeechVoiceData.class);
					vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);
					Intent intent2 = new Intent(getActivity(),
							MusicService.class);
					// 停止播放
					if (vdc.getType().equals(Constants.F_R_MUSIC_STOP_PLAY[0])) {
						intent2.putExtra("play", "pause");
						getActivity().startService(intent2);
					}
					// 继续播放
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_CONTINUE_PLAY[0])) {
						intent2.putExtra("play", "playing");
						intent2.putExtra("id", sp.getInt("currentMusic", 0));
						getActivity().startService(intent2);
					}
					// 下一首
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_NEXT_MUSIC_PLAY[0])) {
						intent2.putExtra("play", "next");
						intent2.putExtra("id", sp.getInt("currentMusic", 0) + 1);
						getActivity().startService(intent2);
					}
					// 上一首
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_LAST_MUSIC_PLAY[0])) {
						int index = sp.getInt("currentMusic", 0) - 1;
						if (index < 0) {
							index = 0;
						}
						intent2.putExtra("play", "last");
						intent2.putExtra("id", index);
						getActivity().startService(intent2);
					} else {
						svd.setCommand(Constants.MAIN_MUSIC_COM);

						Log.i(TAG, intent
								.getStringExtra(Constants.MAIN_MUSIC_ACTION));
						CommonUtil.processBroadcast(getActivity(), svd);
					}

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	/**
	 * 显示
	 * 
	 * @param parent
	 */
	private void showWindow(List<PhoneInfoDataClass> lists) {
		if (popupWindow != null && popupWindow.isShowing()) {
			popupWindow.dismiss();
			groupAdapter.lists.clear();
			popupWindow = null;
		}
		LayoutInflater layoutInflater = (LayoutInflater) getActivity()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		view = layoutInflater.inflate(R.layout.popupwindow_phone_connect, null);

		lv_group = (ListView) view.findViewById(R.id.pw_connect_info);

		groupAdapter = new PhoneConnectAdapter(lists, getActivity());
		lv_group.setAdapter(groupAdapter);
		// 创建一个PopuWidow对象
		popupWindow = new PopupWindow(view, 600, 500);

		// 使其聚集
		popupWindow.setFocusable(true);
		// 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAtLocation(getView(), Gravity.CENTER, 0, 0);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		WindowManager windowManager = (WindowManager) getActivity()
				.getSystemService(Context.WINDOW_SERVICE);
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
		int xPos = windowManager.getDefaultDisplay().getWidth() / 2
				- popupWindow.getWidth() / 2;

		// 弹出popupwindow，背景变暗
		ColorDrawable cd = new ColorDrawable(0x000000);
		popupWindow.setBackgroundDrawable(cd);
		WindowManager.LayoutParams lp = getActivity().getWindow()
				.getAttributes();
		lp.alpha = 0.4f;
		getActivity().getWindow().setAttributes(lp);

		popupWindow.showAsDropDown(getActivity().findViewById(1), xPos, 0);
	}

	// popupwindow消失之后，背景恢复
	public void onDismiss() {
		WindowManager.LayoutParams lp = getActivity().getWindow()
				.getAttributes();
		lp.alpha = 1f;
		getActivity().getWindow().setAttributes(lp);
	}

	/**
	 * 广播过滤器
	 */
	private static IntentFilter phoneInfoIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.MAIN_PHONE_ACTION);
		intentFilter.addAction(Constants.MAIN_NAVI_ACTION);
		intentFilter.addAction(Constants.MAIN_OBD_ACTION);
		intentFilter.addAction(Constants.MAIN_RETURN_HOME_ACTION);
		intentFilter.addAction(Constants.MODEL_PHONE_ACTION);
		intentFilter.addAction(Constants.MODEL_PHONE_NAME_ACTION);
		intentFilter.addAction(Constants.MODEL_PHONE_ITEM_CHOOSE_ACTION);
		intentFilter.addAction(Constants.COMMON_UTIL_ACTION);
		intentFilter.addAction(Constants.MAIN_MUSIC_ACTION);
		return intentFilter;
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onResume() {
		getActivity().registerReceiver(phoneReceiver, phoneInfoIntentFilter());
		super.onResume();

	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onPause() {
		super.onPause();
		getActivity().unregisterReceiver(phoneReceiver);
		// if (svc != null)
		// svc.destroy();
		// if (svr != null)
		// svc.destroy();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 发送广播，在界面上进行修改mainActivity
	 */
	public void processBroadcast(Context context, String name) {
		Log.d(TAG, "phoneFragment---------");
		Intent intentAction = new Intent(Constants.MSG_SEND);
		intentAction.putExtra("NMESSAGE", name);
		context.sendBroadcast(intentAction);
	}

	public void sendMsg(int command, String content) {
		Gson gson = new Gson();
		DataMoreLevelClass dmlc = new DataMoreLevelClass();

		dmlc.setCommand(command);
		dmlc.setContent(content);

		String str = gson.toJson(dmlc);
		PMessage pm = new PMessage();
		pm.command = Constants.MODEL_PHONE_COM;
		pm.message = str;
		pm.fromname = "a";
		pm.toname = "b";
		String str2 = gson.toJson(pm);
		processBroadcast(getActivity(), str2);
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		if (popupWindow != null && popupWindow.isShowing()) {
			onDismiss();
			popupWindow.dismiss();
		}
		onTelTime = 0;
		if (timer != null) {
			timer.cancel();
		}
		super.onDestroyView();
	}
}
